/**
 * 
 */
package ro.dta.idbi.ui.patterns;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;

import ro.dta.idbi.interfaces.sql.ISqlColumn;
import ro.dta.idbi.interfaces.sql.ISqlConstruct;
import ro.dta.idbi.interfaces.ui.IMainFrame;
import ro.dta.idbi.patterns.ColToTable;
import ro.dta.idbi.ui.sql.SqlColumnCell;
import ro.dta.idbi.ui.sql.SqlForeignKeyCell;
import ro.dta.idbi.ui.sql.SqlGraph;
import ro.dta.idbi.ui.sql.SqlTableCell;
import uk.ac.ic.doc.automed.reps.Schema;

import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxEventSource.mxIEventListener;

/**
 * UI for the column to table transformation pattern
 * 
 * @author Tudor Dobrila
 * 
 */
public class ColToTableDialog extends AbstractPatternDialog {

	private static final long serialVersionUID = 8182591796236841599L;

	private static final Logger LOGGER = Logger.getLogger("com.dta.idbi.patterns.ui.ColToTableDialog");

	/**
	 * Check if the current pattern can be applied over a given set of objects
	 * 
	 * Used to check if the items selected by the user in the UI can be used to
	 * apply this transformation pattern over them
	 * 
	 * @param schema
	 *            Schema in the context of which to check the validity of the
	 *            array of objects
	 * @param objects
	 *            Set of objects
	 * @return True if pattern can be applied over set of objects, false
	 *         otherwise
	 */
	public static boolean isValid(final Schema schema, final Object[] objects) {
		if (objects.length != 1 || !(objects[0] instanceof ISqlColumn)) {
			return false;
		}

		final ISqlColumn col = (ISqlColumn) objects[0];
		return !col.isNullable();
	}

	/**
	 * Name of the parent table holding the column
	 */
	private transient String parentName;

	/**
	 * FK edge between the original table and the newly created table
	 */
	private transient SqlForeignKeyCell foreignKey;

	/**
	 * Column to table dialog class constructor
	 * 
	 * @param parentFrame
	 *            Parent frame of this dialog
	 * @param schema
	 *            Schema over which the transformation is applied
	 * @param element
	 *            Sql construct(s) over which the transformation is applied
	 * @param beforeLabel
	 *            Label for the before diagram
	 * @param afterLabel
	 *            Label for the transformed diagram
	 */
	public ColToTableDialog(final IMainFrame parentFrame, final Schema schema, final ISqlConstruct[] element,
			final JLabel beforeLabel, final JLabel afterLabel) {
		super(parentFrame, schema, element, beforeLabel, afterLabel);

		if (!isValid(schema, element)) {
			throw new IllegalArgumentException("This pattern can't be applied to the given elements");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ro.dta.idbi.ui.patterns.TransformationDialog#createOriginalDiagram()
	 */
	@Override
	protected mxGraphComponent createOriginalDiagram() {
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			final SqlTableCell parentTable = (SqlTableCell) ((SqlColumnCell) element[0]).getParent();
			final SqlTableCell newTable = (SqlTableCell) parentTable.clone();
			final ISqlColumn col = newTable.getColumn(element[0].getValue().toString());
			col.setStyle("SEL_COL");

			final mxGeometry newGeometry = new mxGeometry(5, 5, element[0].getGeometry().getWidth(),
					element[0].getGeometry().getHeight());
			newTable.setGeometry(newGeometry);
			newTable.layout(graph);
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ro.dta.idbi.ui.patterns.TransformationDialog#createTransformedDiagram()
	 */
	@Override
	protected mxGraphComponent createTransformedDiagram() {
		initialise();

		final SqlGraph graph = new EditableGraph();
		graph.getModel().beginUpdate();

		SqlTableCell newTable = null;
		SqlTableCell parentTable = null;
		try {
			SqlTableCell origTable = null;

			parentTable = (SqlTableCell) ((SqlColumnCell) element[0]).getParent();
			origTable = (SqlTableCell) parentTable.clone();
			final ISqlColumn col = origTable.getColumn(element[0].getValue().toString());

			final mxGeometry newGeometry = new mxGeometry(5, 5, element[0].getGeometry().getWidth(),
					element[0].getGeometry().getHeight());
			origTable.setGeometry(newGeometry);
			origTable.layout(graph);

			// Create new table
			final mxGeometry geom = new mxGeometry(200, 5, element[0].getGeometry().getWidth(), element[0]
					.getGeometry().getHeight());
			newTable = new SqlTableCell(null, null, "", "newTable", geom, "SEL_TABLE");
			final ISqlColumn col2 = (ISqlColumn) col.clone();
			col2.setStyle("PRIMARYKEY");
			newTable.addColumn(col2);
			newTable.relayout(graph);

			final String fkName = parentName + "_isa_newTable_fk";
			foreignKey = new SqlForeignKeyCell(null, null, "", fkName, origTable, newTable, "FK_EDGE");
			graph.addCell(foreignKey, graph.getDefaultParent());
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			final mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
			layout.execute(graph.getDefaultParent());
			graph.getModel().endUpdate();
		}

		final mxGraphComponent graphComponent = new mxGraphComponent(graph);
		graphComponent.setEnterStopsCellEditing(true);
		graphComponent.addListener(mxEvent.LABEL_CHANGED, new mxIEventListener() {

			@Override
			public void invoke(final Object arg0, final mxEventObject arg1) {
				final SqlTableCell table = (SqlTableCell) arg1.getProperty("cell");
				final StringBuilder builder = new StringBuilder(ColToTable.COMMAND);
				builder.append(" (<<").append(parentName).append(",");
				builder.append(element[0].getValue().toString()).append(">>, <<");
				builder.append(table.getValue()).append(">>)");
				macroField.setText(builder.toString());

				final String fkName = parentName + "_isa_" + table.getValue() + "_fk";
				foreignKey.setValue(fkName);

				graphComponent.revalidate();
				graphComponent.repaint();
			}
		});
		if (newTable != null) {
			graphComponent.startEditingAtCell(newTable);
		}

		return graphComponent;
	}

	private void initialise() {
		final SqlTableCell parent = (SqlTableCell) ((SqlColumnCell) element[0]).getParent();
		parentName = parent.getValue().toString();
		macroField.setText(ColToTable.COMMAND + " (<<" + parentName + "," + element[0].getValue().toString()
				+ ">>, <<newTable>>)");
	}
}
